package org.qhhc.hashmapandtable;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class HashtableTest {
    // 测试参数配置
    private static final int THREAD_COUNT = 10;     // 并发线程数
    private static final int OPERATIONS_PER_THREAD = 500_000; // 每个线程操作次数

    public static void main(String[] args) throws InterruptedException {
        // 测试Hashtable性能
        testMapPerformance(new Hashtable<>(), "Hashtable");

        // 测试HashMap性能（非线程安全，仅作对比）
        testMapPerformance(new HashMap<>(), "HashMap");
    }

    private static void testMapPerformance(Object mapInstance, String label) throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT);
        long startTime = System.nanoTime();

        // 创建并发任务
        for (int i = 0; i < THREAD_COUNT; i++) {
            executor.execute(() -> {
                if (mapInstance instanceof Hashtable) {
                    Hashtable<Integer, String> hashtable = (Hashtable<Integer, String>) mapInstance;
                    for (int j = 0; j < OPERATIONS_PER_THREAD; j++) {
                        hashtable.put(j % 1000, "Value" + j); // 限键范围增加哈希碰撞
                        hashtable.get(j % 1000);
                    }
                } else if (mapInstance instanceof HashMap) {
                    HashMap<Integer, String> hashMap = (HashMap<Integer, String>) mapInstance;
                    for (int j = 0; j < OPERATIONS_PER_THREAD; j++) {
                        hashMap.put(j % 1000, "Value" + j);
                        hashMap.get(j % 1000);
                    }
                }
            });
        }

        executor.shutdown();
        executor.awaitTermination(5, TimeUnit.MINUTES);

        long duration = (System.nanoTime() - startTime) / 1_000_000;
        System.out.println(label + " 总耗时：" + duration + "ms");
    }
}